//
//  Utils.m
//  JiaoX
//
//  Created by jiaoxiu－004 on 14/11/12.
//  Copyright (c) 2014年 北京娇羞科技有限公司. All rights reserved.
//

#import "Utils.h"
#import "UserDefaultsHelper.h"
#import "JXWebViewController.h"
#import "RegexKitLite.h"
#import "JXNavigationController.h"
#import "JXLoginRegistCheckController.h"
#import "JXReviewsController.h"
#import "JXLoginRegistCheckController.h"
#import "JXProdDetailCtl.h"
#import "JXProdListController.h"
#import "Reachability.h"
#import "JXOldHomeController.h"
#import "JXVolumeCtrl.h"
#import "JXMinePostsCtl.h"
#import "MJRefresh.h"
#import "NSString+Extension.h"
#import "JXComtDetailCtl.h"
#import "JXPostsDetailCtl.h"
#import "JXPostsListCtl.h"

#import "JXShakeCtl.h"
@implementation Utils

+(NSString *)getAppVersion{
    // 获得当前打开软件的版本号
    NSString *versionKey = (__bridge NSString *)kCFBundleVersionKey;
    return [NSBundle mainBundle].infoDictionary[versionKey];
}

+(NSString *)getCurrentTime{
    UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
    return [NSString stringWithFormat:@"%llu", recordTime];
}

+(NSString *)getImei{
    
    NSString *imei = [UserDefaultsHelper stringForKey:KEY_UUID];
    if([self isBlankString:imei]){
        //获取一个uuid，然后存入userdefault
        imei = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [UserDefaultsHelper setObject:imei forKey:KEY_UUID];
    }
    return imei;
}



+ (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if(![string isKindOfClass:[NSString class]]){
        string = [NSString stringWithFormat:@"%@",string];
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

+(BOOL)dealUrlWithController:(UIViewController *)controller url:(NSString *)url title:(NSString *)title fromWebView:(BOOL)isFromWebView{
    if([url hasPrefix:@"http"] && !isFromWebView){
        //以http开头，需要跳转到webview界面
        
        if ([url rangeOfString:@"needLogin"].location !=NSNotFound && TOKEN) {
            url = [NSString stringWithFormat:@"%@&token=%@",url,TOKEN];
        }
        JXWebViewController *webview = [JXWebViewController initWithUrl:url title:title];
        [controller.navigationController pushViewController:webview animated:YES];
    }else if([url hasPrefix:@"jiaoxiu"]){
        if([url rangeOfString:@"productid="].location != NSNotFound){
            NSString *regexString  = @"productid=([0-9]*)";
            NSString *prodId = [url stringByMatching:regexString];
            prodId = [prodId substringFromIndex:[prodId rangeOfString:@"="].location+1];
            JXLog(@"找到了prodId = %@",prodId);
            //跳到商品详情
            JXProdDetailCtl *ctrl = [[JXProdDetailCtl alloc]initWithPordId:prodId];
            [controller.navigationController pushViewController:ctrl animated:YES];
        }else if([url rangeOfString:@"labelid="].location != NSNotFound){
            NSString *regexString  = @"labelid=([0-9]*)";
            NSString *labelId = [url stringByMatching:regexString];
            labelId = [labelId substringFromIndex:[labelId rangeOfString:@"="].location+1];
            JXLog(@"找到了labelId = %@",labelId);
            //跳转到商品列表
            JXProdListController *ctrl = [[JXProdListController alloc]initWithRequestId:labelId type:JXProdListRequestTypeCategory];
            [controller.navigationController pushViewController:ctrl animated:YES];
        }else if([url rangeOfString:@"brandid="].location != NSNotFound){
            NSString *regexString  = @"brandid=([0-9]*)";
            NSString *brandId = [url stringByMatching:regexString];
            brandId = [brandId substringFromIndex:[brandId rangeOfString:@"="].location+1];
            JXLog(@"找到了brandId = %@",brandId);
            //跳转到商品列表
            JXProdListController *ctrl = [[JXProdListController alloc]initWithRequestId:brandId type:JXProdListRequestTypeBrand];
            [controller.navigationController pushViewController:ctrl animated:YES];
        }else if([url rangeOfString:@"postsid="].location != NSNotFound){
            NSString *regexString  = @"postsid=([0-9]*)";
            NSString *postsId = [url stringByMatching:regexString];
            postsId = [postsId substringFromIndex:[postsId rangeOfString:@"="].location+1];
            JXLog(@"找到了postsid = %@",postsId);
            //跳转到帖子详情
            JXPostsDetailCtl *ctl = [[JXPostsDetailCtl alloc]initWithPostId:postsId];
            [controller.navigationController pushViewController:ctl animated:YES];
        }else if([url rangeOfString:@"reviewsid="].location != NSNotFound){
            NSString *regexString  = @"reviewsid=([0-9]*)";
            NSString *reviewsId = [url stringByMatching:regexString];
            reviewsId = [reviewsId substringFromIndex:[reviewsId rangeOfString:@"="].location+1];
            JXLog(@"找到了reviewsid = %@",reviewsId);
            //跳转到评测
            JXReviewsController *reviews = [JXReviewsController initWithReviewId:reviewsId title:@"达人评测" reviewsTitle:@"" shareImgUrl:@""] ;
            [controller.navigationController pushViewController:reviews animated:YES];
        }else if([url rangeOfString:@"poolsid="].location != NSNotFound){
            NSString *regexString  = @"poolsid=([0-9]*)";
            NSString *poolsid = [url stringByMatching:regexString];
            poolsid = [poolsid substringFromIndex:[poolsid rangeOfString:@"="].location+1];
            JXLog(@"找到了poolsid = %@",poolsid);
            //跳转到池子(其实我也不明白池子是个啥东西。问春哥去)
            JXProdListController *ctrl = [[JXProdListController alloc]initWithRequestId:poolsid type:JXProdListRequestTypePools];
            [controller.navigationController pushViewController:ctrl animated:YES];
        }else if([url rangeOfString:@"moduleId="].location != NSNotFound){
            NSString *regexString  = @"moduleId=([0-9]*)";
            NSString *moduleId = [url stringByMatching:regexString];
            moduleId = [moduleId substringFromIndex:[moduleId rangeOfString:@"="].location+1];
            JXLog(@"找到了moduleId = %@",moduleId);
            if ([moduleId isEqualToString:@"0"]) {
                //跳到论坛首页
                [[NSNotificationCenter defaultCenter] postNotificationName:@"to_forum" object:nil];
            }else{
                if ([Utils isBlankString:moduleId]) {
                    return NO;
                }
                JXPostsListCtl *ctl = [[JXPostsListCtl alloc]initWithModelId:moduleId];
                [controller.navigationController pushViewController:ctl animated:YES];
            }
        }else if([url rangeOfString:@"homepage="].location != NSNotFound){
            //老首页
            JXOldHomeController *ctrl = [[JXOldHomeController alloc]init];
            [controller.navigationController pushViewController:ctrl animated:YES];
        }else if ([url rangeOfString:@"shakeId"].location != NSNotFound){
            JXShakeCtl *ctrl = [[JXShakeCtl alloc]init];
            [controller.navigationController pushViewController:ctrl animated:YES];
        }else if ([url rangeOfString:@"loginId"].location != NSNotFound){
            //登录
            JXNavigationController *ctrl = [[JXNavigationController alloc] initWithRootViewController:[[JXLoginRegistCheckController alloc] init]];
            [controller presentViewController:ctrl animated:YES completion:nil];
        }else if([url rangeOfString:@"voucherId"].location !=NSNotFound){
            //跳转到代金券列表页
            JXVolumeCtrl *ctrl = [[JXVolumeCtrl alloc]init];
            [controller.navigationController pushViewController:ctrl animated:YES];
        }
        return NO;
    }
    //返回yes会继续去加载网页，返回No不会去继续加载网页
    //返回NO代表自己处理,不用webview处理
    return YES;
}
/**
 *  保存用户信息
 *
 *  @param result 用户信息
 */
+(void)clearUserInfo{
    [UserDefaultsHelper setObject:nil forKey:KEY_APPTOKEN];
    [UserDefaultsHelper setObject:nil forKey:KEY_SERVER_SECRET_KEY];
    [UserDefaultsHelper setObject:nil forKey:KEY_USER_NAME];
    [UserDefaultsHelper setObject:nil forKey:KEY_USER_ID];
    [UserDefaultsHelper setObject:nil forKey:KEY_NICK_NAME];
    [UserDefaultsHelper setObject:nil forKey:KEY_PHONE_CODE];
    [UserDefaultsHelper setObject:nil forKey:KEY_USER_GENDER];
    [UserDefaultsHelper setObject:nil forKey:KEY_USER_IMG];
    [UserDefaultsHelper setObject:nil forKey:KEY_USER_LEVEL];
}


+(NSAttributedString *)getAttribtString:(NSString *)string attrRangs:(NSDictionary *)rangs{
    
    NSAttributedString *str = [[NSAttributedString alloc]initWithString:string];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc]initWithAttributedString:str];
    
    for (NSString *key in rangs) {
        if([rangs[key] isKindOfClass:[UIColor class]])
            [text addAttribute:NSForegroundColorAttributeName value: rangs[key] range:NSRangeFromString(key)];
        if ([rangs[key] isKindOfClass:[UIFont class]]) {
            [text addAttribute:NSFontAttributeName value: rangs[key] range:NSRangeFromString(key)];
        }
    }
    return text;
}

+(BOOL)isPhoneNumber:(NSString *)phoneNum{
    NSString *regEx = @"\\b(1)[34578][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\\b";
    return [phoneNum isMatchedByRegex:regEx];
}

+(void)setSeparatorInsetWithTableView:(UITableView *)tableView insets:(UIEdgeInsets)insets{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:insets];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:insets];
    }
}

+(BOOL)isWifi{
    BOOL result = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            result = NO;
            break;
        case ReachableViaWiFi:
            result = YES;
            break;
        case ReachableViaWWAN:
            result = NO;
            break;
    }
    return result;
}

+(BOOL)isHaveNetWorking{
    NetworkStatus status = [[Reachability reachabilityWithHostName:@"www.apple.com"] currentReachabilityStatus];
    if (status == NotReachable) {
        return NO;
    }else{
        return YES;
    }
}

+(BOOL)isCanLoadPic{
    if ([Utils isWifi]) {
        return YES;
    }else{
        return [UserDefaultsHelper boolForKey:KEY_SHOW_PIC];
    }
}

+(void) saveUserInfo:(UserInfo *)result{
    [UserDefaultsHelper setObject:[result userName] forKey:KEY_USER_NAME];
    [UserDefaultsHelper setObject:[result userId] forKey:KEY_USER_ID];
    [UserDefaultsHelper setObject:[result nickName] forKey:KEY_NICK_NAME];
    [UserDefaultsHelper setObject:[result phoneCode] forKey:KEY_PHONE_CODE];
    [UserDefaultsHelper setObject:[result userGender] forKey:KEY_USER_GENDER];
    [UserDefaultsHelper setObject:[result userImg] forKey:KEY_USER_IMG];
    [UserDefaultsHelper setObject:[NSNumber numberWithInteger:[result level]] forKey:KEY_USER_LEVEL];
}

+(UserInfo *)currentUserInfo{
    UserInfo * userInfo= [[UserInfo alloc]init];
    [userInfo setUserName:[UserDefaultsHelper stringForKey:KEY_USER_NAME]];
    [userInfo setUserId:[UserDefaultsHelper stringForKey:KEY_USER_ID]];
    [userInfo setNickName:[UserDefaultsHelper stringForKey:KEY_NICK_NAME]];
    [userInfo setPhoneCode:[UserDefaultsHelper stringForKey:KEY_PHONE_CODE]];
    [userInfo setUserGender:[UserDefaultsHelper stringForKey:KEY_USER_GENDER]];
    [userInfo setUserImg:[UserDefaultsHelper stringForKey:KEY_USER_IMG]];
    [userInfo setLevel:[UserDefaultsHelper integerForKey:KEY_USER_LEVEL]];
    return userInfo;
    
}

+(NSUInteger)getLengthWithStr:(NSString *)str{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData* da = [str dataUsingEncoding:enc];
    return [da length];
}

+(void)openPush{
    UIApplication *application = [UIApplication sharedApplication];
    if (iOS8) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert
                                                | UIUserNotificationTypeBadge
                                                | UIUserNotificationTypeSound
                                                                                 categories:nil];
        [application registerUserNotificationSettings:settings];
        [application registerForRemoteNotifications];
    }else{
        [application registerForRemoteNotificationTypes:
         UIRemoteNotificationTypeBadge |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeSound];
    }
}

+(void)closePush{
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
}

+(BOOL)isAllowPush{
    
    if(iOS8){
        UIUserNotificationType types = [[UIApplication sharedApplication] currentUserNotificationSettings].types;
        if (types == UIUserNotificationTypeNone){
            return NO;
        }else{
            return YES;
        }
    }else{
//        UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
//        if (types == UIRemoteNotificationTypeNone){
//            return NO;
//        }else{
//            return YES;
//        }
        return YES;
    }
    return NO;
}


+ (UIViewController *)getActivityViewController
{
    UIViewController* activityViewController = nil;
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if(window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow *tmpWin in windows)
        {
            if(tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    NSArray *viewsArray = [window subviews];
    if([viewsArray count] > 0)
    {
        UIView *frontView = [viewsArray objectAtIndex:0];
        
        id nextResponder = [frontView nextResponder];
        
        if([nextResponder isKindOfClass:[UIViewController class]])
        {
            activityViewController = nextResponder;
        }
        else
        {
            activityViewController = window.rootViewController;
        }
    }
    
    return activityViewController;
}

+ (void)refreshComplete:(UITableView *)tableView{
    [tableView headerEndRefreshing];
    [tableView footerEndRefreshing];
}

+ (NSString *)getUPYSaveKey{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"/yyyyMM/dd"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    //生成6位的随机字符串
    NSString *dataPoint = [NSString randomStringWithLength:6];
    
    return [NSString stringWithFormat:@"/posts/pst%@/%.0f%@",currentDateStr,[[NSDate date] timeIntervalSince1970],dataPoint];
}

+(NSString *)millisecs2DateString:(int64_t)timestamp{
    int64_t nowLong = [[NSDate date] timeIntervalSince1970]*1000 ;
    int64_t seconds = (nowLong - timestamp) / 1000;
    if (seconds <= 60) {
        return @"刚刚";
    } else if (seconds < 60 * 60) {
        return [NSString stringWithFormat:@"%d分钟前",(int) (seconds / 60)];
    } else if (seconds < 60 * 60 * 24) {
        return [NSString stringWithFormat:@"%d小时前",(int) (seconds / 60 / 60)];
    } else {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式,这里可以设置成自己需要的格式
        [dateFormatter setDateFormat:@"MMM-dd HH:mm"];
        return [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timestamp]];
    }
    return nil;
}

+(void)dealNotiWithController:(UIViewController *)controller notiDic:(NSDictionary *)dic isForgorund:(BOOL)isForgorund{
    if (isForgorund) {
        //处理推送消息
        switch ([dic[@"messageType"] integerValue]) {
            case -2://帖子被回复
            case -3:{//评论被回复
                NSString *comtId = dic[@"value"][0];//评论id；
                NSString *replyId = dic[@"value"][1];//帖子id；
                JXComtDetailCtl *ctl = [[JXComtDetailCtl alloc]initWithComtId:comtId ReplyType:REPLY_TYPE_POSTSID replyId:replyId startFrom:0 mainComtInfo:nil];
                [controller.navigationController pushViewController:ctl animated:YES];
                break;
            }
            case -4:{//评测被回复
                //这版不做
                //            NSString *comtId = dic[@"value"][0];//评论id；
                //            NSString *replyId = dic[@"value"][1];//测评id；
                //            JXComtDetailCtl *ctl = [[JXComtDetailCtl alloc]initWithComtId:comtId ReplyType:REPLY_TYPE_REVIEWSID replyId:replyId startFrom:0 mainComtInfo:nil];
                //            [controller.navigationController pushViewController:ctl animated:YES];
                break;
            }
            case 7://帖子审核通过了
            {
                JXMinePostsCtl *ctl = [[JXMinePostsCtl alloc]initWithModelList:nil];
                [controller.navigationController pushViewController:ctl animated:YES];
                break;
            }
            default:
                break;
        }
    }else{
        switch ([dic[@"messageType"] integerValue]) {
            case -2:{//帖子被回复
                NSInteger integer = [UserDefaultsHelper integerForKey:KEY_REPLY_MINE_POST_NOTI_NUM];
                integer ++;
                [UserDefaultsHelper setInteger:integer forKey:KEY_REPLY_MINE_POST_NOTI_NUM];
                break;
            }
            case -3:{//评论被回复
                NSInteger integer = [UserDefaultsHelper integerForKey:KEY_REPLY_MINE_COMT_NOTI_NUM];
                integer ++;
                [UserDefaultsHelper setInteger:integer forKey:KEY_REPLY_MINE_COMT_NOTI_NUM];
                break;
            }
            case -4:{//评测被回复
                //这版不做
                //            NSString *comtId = dic[@"value"][0];//评论id；
                //            NSString *replyId = dic[@"value"][1];//测评id；
                //            JXComtDetailCtl *ctl = [[JXComtDetailCtl alloc]initWithComtId:comtId ReplyType:REPLY_TYPE_REVIEWSID replyId:replyId startFrom:0 mainComtInfo:nil];
                //            [controller.navigationController pushViewController:ctl animated:YES];
                break;
            }
            case 7://帖子审核通过了
            {
                NSInteger integer = [UserDefaultsHelper integerForKey:KEY_MYPOSTS_NOTI_NUM];
                integer ++;
                [UserDefaultsHelper setInteger:integer forKey:KEY_MYPOSTS_NOTI_NUM];
                break;
            }
            default:
                break;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_UPDATA_BADGE_NUM object:nil];
    }
    
}

/**
 *  分享到微信
 *
 *  @param scene
 */
+(void)shareToWx:(int)scene share_url:(NSString*)share_url share_title:(NSString*)share_title share_desc:(NSString*)share_desc image:(UIImage *)image{
    [[WXClient sharedClient]sendLinkContentWithURlStr:share_url andTitle:share_title andDescription:share_desc andImage:image andScene:scene];
}

+(BOOL)checkColumnExist:(FMDatabase *)db tableName:(NSString *)tableName columnName:(NSString *)columnName{
    //select * from sqlite_master where name = '%@' and sql like '%%%@%%'", new String[]{tableName , "%" + columnName + "%"}
    NSString *sql = [NSString stringWithFormat:@"select * from sqlite_master where name = '%@' and sql like '%%%@%%'",tableName,columnName];
    FMResultSet * countRes = [db executeQuery:sql];
    if ([countRes next]) {
        return YES;
    }
    return NO;
}


+(NSString *)getGenderStrWithGender:(NSString *)gender level:(NSInteger)level isLarge:(BOOL)large{
    NSString *genderImg = @"";
    
    if (large) {
        genderImg = @"ic_gender_unknow";
        //判断是男是女
        if ([gender isEqualToString:@"1"]) {
            genderImg = @"ic_gender_man";
        }else if([gender isEqualToString:@"2"]){
            genderImg = @"ic_gender_woman";
        }
        //判断是否是vip
        if (level) {
            genderImg = [NSString stringWithFormat:@"%@_vip",genderImg];
        }
        return genderImg;
    }else{
        genderImg = @"ic_gender_small_unknow";
        //判断是男是女
        if ([gender isEqualToString:@"1"]) {
            genderImg = @"ic_gender_small_man";
        }else if([gender isEqualToString:@"1"]){
            genderImg = @"ic_gender_small_woman";
        }
        //判断是否是vip
        if (level) {
            genderImg = [NSString stringWithFormat:@"%@_vip",genderImg];
        }
        return genderImg;
    }
}
@end
